import { NavigationProp, RouteProp } from '@react-navigation/native';
import React, { useEffect, useState } from 'react';
import { Image, StyleSheet } from 'react-native';
import DatePicker from '../../../component/DatePicker.tsx';
import { Divider, Text, View } from 'native-base';
import { Touchable } from 'react-native-toast-message/lib/src/components/Touchable';
import { useReactive } from 'ahooks';
import UserRequest from '../../../request/userRequest.ts';
import { Loading } from '../../../component/LoadingOverlay.tsx';
import CustomFlatList from '../../../component/CustomFlatList.tsx';

interface IPointsDetailsProps {
  navigation: NavigationProp<any, 'pointsDetails'>;
  route: RouteProp<{ pointsDetails: any }, 'pointsDetails'>;
}
interface IState {
  year: number;
  month: number;
  integralData: any;
  isLoading: boolean;
  pageNo: number;
  totalPage: number;
  pointsRecordList: IPointsRecordListIsList[];
  reset: () => void;
}
const PointsDetails: React.FC<IPointsDetailsProps> = ({ navigation, route }) => {
  const [isModalVisible, setModalVisible] = useState(false);
  const state = useReactive<IState>({
    year: new Date().getFullYear(),
    month: new Date().getMonth() + 1,
    integralData: { expense: 0, income: 0 },
    isLoading: false,
    pageNo: 1,
    totalPage: 2,
    pointsRecordList: [],
    reset() {
      this.pageNo = 1;
      this.totalPage = 2;
      this.pointsRecordList = [];
    },
  });

  useEffect(() => {
    fetchCountByMonthData();
    fetchPointsRecordList();
  }, []);

  /**
   * 获得积分数据
   */
  const fetchCountByMonthData = () => {
    Loading.show('加载中');
    UserRequest.CountByMonth({ year: state.year, month: state.month })
      .then((res) => {
        state.integralData = res.data;
        Loading.hide();
      })
      .catch(() => Loading.hide());
  };

  /**
   * 获得积分列表数据
   */
  const fetchPointsRecordList = () => {
    const { year, month, pageNo, totalPage } = state;
    if (pageNo <= totalPage) {
      state.isLoading = true;
      UserRequest.PointsRecordList({ year, month, pageNo, pageSize: 10 })
        .then((res) => {
          state.pointsRecordList = [...state.pointsRecordList, ...res.data.list];
          state.totalPage = res.data.totalPage;
          state.pageNo += 1;
          state.isLoading = false;
        })
        .catch(() => (state.isLoading = false));
    }
  };

  const renderItem = (item: IPointsRecordListIsList) => {
    return (
      <View style={styles.card}>
        <Text>{item.createDate}</Text>
        <Text>
          {item.recordType === 1 ? '+' : '-'} {item.points}
        </Text>
      </View>
    );
  };

  return (
    <React.Fragment>
      <View style={styles.root}>
        <View backgroundColor={'#f8ebd9'} height={200}></View>
        <View style={styles.content}>
          <Touchable style={{ borderRadius: 8, paddingHorizontal: 12, paddingVertical: 8, backgroundColor: '#fff', flexDirection: 'row', alignItems: 'center' }} onPress={() => setModalVisible((prevState) => !prevState)}>
            <Text marginRight={2}>
              {state.year}年{state.month}月
            </Text>
            <Image style={{ marginTop: 1 }} resizeMode="cover" source={require('../../../assets/images/user/pointsDetails/point.png')} />
          </Touchable>
          <View flexDirection={'row'} alignItems={'flex-end'}>
            <Text fontSize={42} marginTop={5} fontWeight={'bold'} color={'#b5835a'} marginRight={2}>
              {state.integralData.income - state.integralData.expense >= 0 ? '+' : '-'}
              {state.integralData.income - state.integralData.expense}
            </Text>
            <Text marginBottom={2}>积分</Text>
          </View>
          <View style={styles.card} marginTop={5}>
            <View flex={1} alignItems={'center'}>
              <Text marginBottom={2}>积分获取</Text>
              <Text color={'#b5835a'} fontWeight={'bold'} fontSize={18}>
                + {state.integralData.income}
              </Text>
            </View>
            <Divider width={0.6} bg={'#f8ebd9'} orientation="vertical" />
            <View flex={1} alignItems={'center'}>
              <Text marginBottom={2}>积分支出</Text>
              <Text fontWeight={'bold'} fontSize={18}>
                - {state.integralData.expense}
              </Text>
            </View>
          </View>
        </View>
        <CustomFlatList isRefresh={false} style={{ flex: 1, paddingHorizontal: 16 }} data={state.pointsRecordList} renderItem={({ item }) => renderItem(item)} onEndReached={fetchPointsRecordList} isLoading={state.isLoading} noDataText="没有更多数据了" />
      </View>

      <DatePicker
        show={isModalVisible}
        currentDate={[state.year, state.month]}
        columnsType={['year', 'month']}
        minDate={`2019,01`}
        maxDate={`${new Date().getFullYear()},${new Date().getMonth() + 1}`}
        closeOnClickOverlay
        onClose={() => setModalVisible(false)}
        onConfirm={(date) => {
          state.year = Number(date[0]);
          state.month = Number(date[1]);
          state.reset();
          setModalVisible(false);
          fetchCountByMonthData();
          fetchPointsRecordList();
        }}
        title={'选择时间'}
      />
    </React.Fragment>
  );
};
const styles = StyleSheet.create({
  root: { flex: 1 },
  content: { flex: 1, marginTop: -200, marginBottom: -180, padding: 16, alignItems: 'center' },
  card: { borderRadius: 8, backgroundColor: '#fff', marginBottom: 16, padding: 12, flexDirection: 'row', justifyContent: 'space-between', width: '100%' },
});

export default PointsDetails;
